from fastapi import FastAPI, HTTPException
from tortoise.exceptions import DoesNotExist
from pydantic import BaseModel
from typing import List
import redis.asyncio as redis
from datetime import datetime
from models.user import User
from models.products import Product
from models.history import History
from fastapi import APIRouter

router = APIRouter(tags=["历史记录"])
redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)


class ProductResponse(BaseModel):
    id: int
    name: str
    description: str | None
    price: float
    image_url: str
    video_url: str
    inventory: int
    sales: int
    is_active: bool
    is_hot: bool
    share_count: int
    created_time: datetime
    updated_time: datetime

    class Config:
        from_attributes = True


class HistoryResponse(BaseModel):
    id: int
    user_id: int
    product_id: int
    created_time: datetime
    updated_time: datetime
    browse_time: datetime
    product: ProductResponse
    redis_browse_timestamp: float | None = None

    class Config:
        from_attributes = True


@router.post("/api/history/{user_id}/{product_id}", response_model=HistoryResponse)
# 浏览记录提交
async def record_history(user_id: int, product_id: int):
    try:
        user = await User.get(id=user_id)
        product = await Product.get(id=product_id)
        existing_history = await History.filter(user=user, product=product).first()
        if existing_history:
            existing_history.browse_time = datetime.now()
            existing_history.updated_time = datetime.now()
            await existing_history.save()
            history = existing_history
        else:
            history = await History.create(
                user=user,
                product=product,
                browse_time=datetime.now()
            )
        history_with_related = await History.filter(id=history.id).prefetch_related("product").first()
        await redis_client.zadd(
            f"history:{user_id}",
            {product_id: history.browse_time.timestamp()}
        )
        return history_with_related

    except DoesNotExist:
        raise HTTPException(status_code=404, detail="用户或商品不存在")


@router.get("/api/history/{user_id}", response_model=List[HistoryResponse])
# 浏览记录查询
async def get_history(user_id: int):
    try:
        user = await User.get(id=user_id)
        redis_key = f"history:{user_id}"

        product_id_with_scores = await redis_client.zrevrange(
            redis_key, 0, -1, withscores=True  # withscores=True：同时返回时间戳
        )
        product_info = [(int(pid), score) for pid, score in product_id_with_scores if pid.isdigit()]
        if not product_info:
            return []

        product_ids = [pid for pid, _ in product_info]
        history_records = await History.filter(
            user=user,
            product__id__in=product_ids
        ).prefetch_related("product")

        history_map = {h.product.id: h for h in history_records}

        ordered_history = []
        for pid, timestamp in product_info:
            if pid in history_map:
                history = history_map[pid]
                history.redis_browse_timestamp = timestamp
                ordered_history.append(history)

        return ordered_history
    except DoesNotExist:
        raise HTTPException(status_code=404, detail="用户不存在")
